import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'

// 是否显示重新登录
export const isRelogin = { show: false }

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: "http://192.168.0.102:8080",
  // baseURL: "http://39.170.82.20:8062",
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor  请求拦截器
// request.interceptors.request.use(
//   (config) => {
//     // do something before request is sent

//     if (store.getters.token) {
//       // let each request carry token
//       // ['X-Token'] is a custom headers key
//       // please modify it according to the actual situation
//       config.headers["X-Token"] = getToken();
//     }
//     return config;
//   },
//   (error) => {
//     // do something with request error
//     console.log(error); // for debug
//     return Promise.reject(error);
//   }
// );

// // response interceptor  响应拦截器
// request.interceptors.response.use(
//   /**
//    * If you want to get http information such as headers or status
//    * Please return  response => response
//    */

//   /**
//    * Determine the request status by custom code
//    * Here is just an example
//    * You can also judge the status by HTTP Status Code
//    */
//   (response) => {
//     const res = response.data;

//     // if the custom code is not 20000, it is judged as an error.
//     if (res.code !== 20000) {
//       Message({
//         message: res.message || "Error",
//         type: "error",
//         duration: 5 * 1000,
//       });

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    if (store.getters.token) {
      const url = config.url.replace(process.env.VUE_APP_BASE_API, '')
      if (!store.getters.buttons.includes(url)) {
        // const error = new Error('无权限访问URL ' + url);
        // return Promise.reject(error);
      }
      config.headers['Authorization'] = 'Bearer ' + getToken()
      config.headers['locale'] = store.getters.language
    }
    return config
  },
  (error) => {
    Message.error({ message: error })
  }
)
// 响应拦截器
request.interceptors.response.use(
  (res) => {
    const code = res.data.returnCode || 10000
    const msg = errorCode[code] || res.data.returnMsg || errorCode['default']
    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
      return res.data
    }
    if (code === 10001) {
      if (!isRelogin.show) {
        isRelogin.show = true
        MessageBox.confirm('登录状态已过期，您可以继续留在该页面，或者重新登录', '系统提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          isRelogin.show = false
          store.dispatch('user/logout').then(() => {
            location.href = '/login?redirect=/dashboard'
          })
        }).catch(() => {
          isRelogin.show = false
        })
      }
      return Promise.reject('无效的会话，或者会话已过期，请重新登录。')
    } else if (code === 99999) {
      Message({ message: msg, type: 'error' })
      return Promise.reject(new Error(msg))
    } else if (code !== 10000) {
      Notification.error({ title: msg })
      return Promise.reject('error')
    } else {
      return res.data
    }
  },
  (error) => {
    console.log('err' + error)
    let { message } = error
    if (message === 'Network Error') {
      message = '后端接口连接异常'
    } else if (message.includes('timeout')) {
      message = '系统接口请求超时'
    } else if (message.includes('Request failed with status code')) {
      message = '系统接口' + message.substr(message.length - 3) + '异常'
    }
    Message({ message: message, type: 'error', duration: 5 * 1000 })
    return Promise.reject(error)
  }
)

export default request
